<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/8
 * Time: 17:06
 */

class Purchase_order_model extends CI_Model
{
    public $limit_rows = 10;

    public function _where($param)
    {
        if ($param['purchase_name']) {
            $this->db->where("(po.po_sn = '{$param['purchase_name']}' OR s.suppliers_name LIKE '%{$param['purchase_name']}%')");
        }

        if ($param['po_status']) {
            $this->db->where('po.po_status', $param['po_status']);
        }
    }

    public function order_list($param = array())
    {

        $sql_purchase_goods = $this->db->from('purchase_goods AS pg')->select_sum('pg_number')->where("pg.po_id = po.po_id")->get_compiled_select();

        $this->db->select("po.*,s.suppliers_name,d.delivery_com,d.delivery_url, ({$sql_purchase_goods}) AS goods_number");
        $this->db->from('purchase_order AS po');
        $this->db->join('suppliers AS s', 'po.supp_id = s.suppliers_id', 'left');
        $this->db->join('delivery AS d', 'po.delivery_id = d.delivery_id', 'left');
        $this->db->limit($this->limit_rows,$this->limit_rows * $param['page']);
        $this->db->order_by('po.po_id DESC');

        $this->_where($param);

        $query = $this->db->get();
        $purchase_order = $query->result_array();

        return $purchase_order;
    }

    public function order_info($param)
    {
        $this->db->select('po.*,s.suppliers_name');
        $this->db->from('purchase_order AS po');
        $this->db->join('suppliers AS s', 'po.supp_id = s.suppliers_id', 'left');
        $this->db->where($param);

        $query = $this->db->get();
        return $query->row_array();
    }

    public function order_num($param = array())
    {
        $this->db->from('purchase_order AS po');
        $this->db->join('suppliers AS s', 'po.supp_id = s.suppliers_id', 'left');
        $this->db->join('delivery AS d', 'po.delivery_id = d.delivery_id', 'left');

        $this->_where($param);

        return $this->db->count_all_results();
    }


    public function add_log($data = array())
    {
        $t = time();

        $data_log = array(
            'admin_id' => intval($_SESSION['admin_id']),
            'po_id' => $data['po_id'],
            'po_status' => $data['po_status'],
            'po_info' => $data['info'],
            'add_time' => $t
        );

        $this->db->insert('purchase_order_log', $data_log);


        return $this->db->insert_id();
    }

    public function log_list($po_id = 0)
    {
        $query = $this->db->from('purchase_order_log AS pol')
            ->select('pol.*,a.admin_name')
            ->join('admin AS a', 'pol.admin_id = a.admin_id', 'left')
            ->where('pol.po_id', $po_id)
            ->order_by('pol.add_time DESC')->get();

        $log_list = $query->result_array();

        return $log_list;
    }

    public function batch_create_order($param = array())
    {

        foreach ($param as $row) {
            $this->create_order(array('supp_id' => $row['supp_id'], 'po_info' => ''));
        }

    }

    public function create_order($param = array())
    {

        $sql_purc_goods_where = "pg_status = 0 AND supp_id = '{$param['supp_id']}'";

        $order_info = $this->order_info(array('supp_id' => $param['supp_id'], 'po_status' => 1));

        if ($order_info) {
            $po_id = $order_info['po_id'];
        } else {
            $data = array(
                'supp_id' => $param['supp_id'],
                'po_sn' => $this->erp_get_po_sn(),
                'po_status' => 1,
                'po_info' => $param['po_info'],
                'add_time' => time()
            );
            $this->db->insert('purchase_order', $data);
            $po_id = $this->db->insert_id();

        }

        if ($po_id) {

            //采购商品添加批次ID
            $goods_data = array(
                'po_id' => $po_id,
                'pg_status' => 1
            );
            $this->db->where($sql_purc_goods_where);
            $this->db->update('purchase_goods AS pg', $goods_data);

            //更新批次价格
            $query_price = $this->db->from('purchase_goods')->where("po_id = '{$po_id}'")->select_sum('purc_price')->get();
            $purchase_goods = $query_price->row_array();

            $this->db->where("po_id = '{$po_id}'");
            $this->db->update('purchase_order', array('goods_amount' => $purchase_goods['purc_price']));
        }

        return true;
    }

    /**
     *
     *
     */
    public function check_status($po_id, $po_status, $log_info = '')
    {

        $state = false;

        switch ($po_status) {
            case 2: // 采购中

                $query = $this->db->from('purchase_goods')->where(array(
                    'po_id' => $po_id,
                    'pg_status <= ' => 1
                ))->get();
                $purchase_goods = $query->row_array();

                if (!$purchase_goods) {
                    $this->update_order($po_id, array('po_status' => 2));

                    $log_info .= ($log_info? '<br /> ' : '') . '采购批次设为采购中！';
                    $state = true;
                }
                break;
            case 3: // 采购完
                $query = $this->db->select('po_id,SUM(pg_number) AS pg_number,SUM(inv_number) AS inv_number')
                    ->from('purchase_goods')
                    ->where('po_id', $po_id)->get();
                $po = $query->row_array();

                if ($po['pg_number'] == $po['inv_number']) {
                    $this->update_order($po_id, array('po_status' => 3));

                    $log_info .= ($log_info? '<br /> ' : '') . '采购批次已完成！';
                }

                $state = true;
                break;
            case 4: // 取消采购

                $query = $this->db->from('purchase_goods')->where("po_id = '{$po_id}' AND pg_status != 4")->get();
                $purchase_goods = $query->row_array();

                if (!$purchase_goods) {
                    $this->update_order($po_id, array('po_status' => 4));

                    $log_info .= ($log_info? '<br /> ' : '') . '取消采购批次！';
                }

                break;
        }

        $data = array(
            'po_id' => $po_id,
            'po_status' => $po_status,
            'info' => $log_info
        );
        $this->add_log($data);

        return $state;
    }

    /**
     * 根据批次设置采购产品状态
     *
     */
    public function set_po_status($where = array(), $param = array())
    {

        $data = array();

        if (isset($param['pg_status'])) {
            $data['pg_status'] = $param['pg_status'];
        }


        if ($data) {
            $where['pg_status'] = 1;
            $this->db->where($where);
            $this->db->update('purchase_goods', $data);
            return true;
        }
        return false;

    }


    /**
     * 更新批次
     *
     */
    public function update_order($po_id, $param = array())
    {

        $data = array();

        if (isset($param['po_status'])) {
            $data['po_status'] = $param['po_status'];
        }

        if ($param['ali_invoice_no']) {
            $data['ali_invoice_no'] = $param['ali_invoice_no'];
        }


        if ($data) {
            $this->db->where("po_id = '{$po_id}'");
            $this->db->update('purchase_order', $data);
            return true;
        }
        return false;

    }

    /*
    *生成采购批次号
    */
    function erp_get_po_sn()
    {
        return date('YmdHis', time()) . str_pad(mt_rand(1, 999), 3, '0', STR_PAD_LEFT);
    }
}
